package com.lala.rennigou.controller;

import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.PageInfo;
import com.lala.rennigou.Util.FTPUtil;
import com.lala.rennigou.pojo.EasybuyProduct;
import com.lala.rennigou.pojo.EasybuyUser;
import com.lala.rennigou.service.EasybuyProductService;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

@RestController
public class EasybuyProductController {
    @Autowired
    private EasybuyProductService easybuyProductService;
    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;
    @Autowired
    private SolrClient solrClient;
    public EasybuyUser yanzheng(HttpServletRequest request){
        EasybuyUser easybuyUser=null;
        Cookie[] cookies =  request.getCookies();//获取保存在request的所有cookie
        if(cookies != null){//判断cookies数组是否为空
            for(Cookie cookie : cookies){
                if(cookie.getName().equals("user")){//通过for循环找到想要获取的值
                    Map<String ,Object> map=(Map<String ,Object>) redisTemplate.opsForValue().get(cookie.getValue());
                    if(map!=null){
                        easybuyUser=(EasybuyUser)map.get("user");
                    }
                }
            }
        }
        return easybuyUser;
    }
    @RequestMapping("/tdSP")
    public Object tdSP(int id,int pageNum,int pageSize){
        PageInfo<EasybuyProduct> pageInfo = easybuyProductService.seleceByCategoryLevel3Id(id,pageNum,pageSize);
        return JSONArray.toJSON(pageInfo);
    }
    @RequestMapping("/spXQ")
    public Object spXQ(int id){
        EasybuyProduct easybuyProduct = easybuyProductService.selectById(id);
        return JSONArray.toJSON(easybuyProduct);
    }

    @RequestMapping("/scSP")
    public Object scSP(int id, HttpServletRequest request){
        EasybuyUser easybuyUser=yanzheng(request);
        Map<String ,Object> m=new HashMap<>();
        if (easybuyUser!=null){
            List<EasybuyProduct> l=(List<EasybuyProduct>)redisTemplate.opsForValue().get(easybuyUser.getLoginname());
            EasybuyProduct easybuyProduct = easybuyProductService.selectById(id);
           if (l!=null){
               for (EasybuyProduct e:l){
                   if (id==Integer.parseInt(e.getId())){
                       m.put("msg","您收藏过了，不用再点收藏了");
                       return JSONArray.toJSON(m);
                   }
               }
               if (l.size()>5) {l.remove(0);}
               l.add(easybuyProduct);
               redisTemplate.opsForValue().set(easybuyUser.getLoginname(),l);
           }else {
               List<EasybuyProduct> ll=new ArrayList<>();
               ll.add(easybuyProduct);
               redisTemplate.opsForValue().set(easybuyUser.getLoginname(),ll);
           }

            m.put("msg","收藏成功");
            return JSONArray.toJSON(m);
        }else {
            m.put("msg","请登陆后再收藏");
            return JSONArray.toJSON(m);
        }

    }
    @RequestMapping("/shoucang")
    public Object shoucang(HttpServletRequest request){
        EasybuyUser easybuyUser=yanzheng(request);
        List<EasybuyProduct> l=null;
        if (easybuyUser!=null){
             l=(List<EasybuyProduct>)redisTemplate.opsForValue().get(easybuyUser.getLoginname());
            return JSONArray.toJSON(l);
        }else {
            return JSONArray.toJSON(l);
        }

    }

    @RequestMapping("/gwcSP")
    private Object gwcSP(HttpServletRequest request, int id, @RequestParam(value = "number",required = false)Integer number){
        EasybuyUser easybuyUser=yanzheng(request);
        Map<String ,Object> m=new HashMap<>();
        Map<Object ,Object> gwc=new HashMap<>();
        Map<Object ,Object> num=new HashMap<>();
        //由用户登录，通过用户登录的loginname（唯一）取出用户的购物车
        // 如果没有用户登录，则 返回登录后再将商品加入购物车
        if (easybuyUser!=null){
            //拿到用户的购物车
            Map<String,Object> map=(Map<String,Object>)redisTemplate.opsForValue().get(easybuyUser.getLoginname()+"la");
            //查询出该商品的信息
            EasybuyProduct easybuyProduct = easybuyProductService.selectById(id);
            //如果用户是第一次加入购物车，则新new一个list
            if (map!=null){
                //拿到用户购物车里所有的商品及数量
                List<EasybuyProduct> l=(List<EasybuyProduct>)map.get("list");
                   boolean flag=true;
                   //循环，判断商品是否第一次加入购物车，是则只增加数量，不是就将商品存入list
                   for (EasybuyProduct e:l) {
                       if (id == Integer.parseInt(e.getId())) {
                           flag = false;
                           if (number == null) {
                               if (e.getStock()<e.getNum()+1){
                                   m.put("msg","库存不足");
                                   return JSONArray.toJSON(m);
                               }
                               e.setNum(e.getNum() + 1);
                           } else {
                               if (e.getStock()<e.getNum()+number){
                                   m.put("msg","库存不足");
                                   return JSONArray.toJSON(m);
                               }
                               e.setNum(e.getNum() + number);
                           }
                           gwc.put("list", l);

                       }
                   }
                   //商品第一次进入购物车
                   if (flag){
                       if (number==null){
                           easybuyProduct.setNum(1);
                       }else {
                           easybuyProduct.setNum(number);
                       }
                       l.add(easybuyProduct);
                       gwc.put("list",l);
                   }
            }else {
                List<EasybuyProduct> ll=new ArrayList<>();
                if (number==null){
                    easybuyProduct.setNum(1);
                }else {
                easybuyProduct.setNum(number);
                }
                ll.add(easybuyProduct);
                gwc.put("list",ll);
            }
            redisTemplate.opsForValue().set(easybuyUser.getLoginname()+"la",gwc);
            m.put("msg","加入购物车成功");
            return JSONArray.toJSON(m);
        }else {
            m.put("msg","请登陆后再加入购物车");
            return JSONArray.toJSON(m);
        }
    }

    //从redis中取出当前登录用户的购物车，如果没登陆返回空，页面不显示
    @RequestMapping("/gouwuche")
    public Object gouwuche(HttpServletRequest request){
        EasybuyUser easybuyUser=yanzheng(request);
        Map<String,Object> map=null;
        if(easybuyUser!=null){
            map=(Map<String,Object>)redisTemplate.opsForValue().get(easybuyUser.getLoginname()+"la");

        }
        return JSONArray.toJSON(map);
    }

    @RequestMapping("/fenci")
    private Object fenci(String c,int p) throws IOException, SolrServerException {
        //创建查询
        SolrQuery solrQuery =new SolrQuery();
        //添加查询
        if (c==""){
            solrQuery.setQuery("*:*");
        }else {
            solrQuery.setQuery("name_ik:"+c);
        }

        //添加排序
        solrQuery.addSort("price_f", SolrQuery.ORDER.desc);
//添加分页
        solrQuery.setStart(p);
        solrQuery.setRows(4);
        //添加高亮
        solrQuery.setHighlight(true);
        solrQuery.addHighlightField("name_ik");
        solrQuery.setHighlightSimplePre("<font color=\"red\">");
        solrQuery.setHighlightSimplePost("</font>");
        //查询
        QueryResponse qr = solrClient.query(solrQuery);
        Map<String, Map<String, List<String>>> map = qr.getHighlighting();
        List<EasybuyProduct> list=qr.getBeans(EasybuyProduct.class);
        Map<String,Object> m=new HashMap<>();
        m.put("map",map);
        m.put("list",list);
        return JSONArray.toJSON(m);
//        for (EasybuyProduct products:list){
//            System.out.println(map.get(products.getId()).get("name_ik")+"\t"+products.getName()+"\t"+products.getPrice());
//        }
    }

    @RequestMapping("/shanchu")
    public Object shanchu(int id,HttpServletRequest request){
        EasybuyUser easybuyUser=yanzheng(request);
        Map<String,Object> map=(Map<String,Object>)redisTemplate.opsForValue().get(easybuyUser.getLoginname()+"la");
        List<EasybuyProduct> list = (List<EasybuyProduct>)map.get("list");
//        Map<String , Object> m=(Map<String , Object>)map.get("num");
        for (int i=0;i<list.size();i++){
            if (Integer.parseInt(list.get(i).getId())==id){
//                m.remove(list.get(i).getId());
                list.remove(i);
            }
        }
        map.put("list",list);
//        map.put("num",m);
        redisTemplate.opsForValue().set(easybuyUser.getLoginname()+"la",map);
        Map<String ,String> mm=new HashMap<>();
        mm.put("msg","删除成功");
        return JSONArray.toJSON(mm);
    }

    @RequestMapping("/xiugaiNum")
    private Object xiugaiNum(int id,int num,HttpServletRequest request){
        EasybuyUser easybuyUser=yanzheng(request);
        Map<String,Object> map=(Map<String,Object>)redisTemplate.opsForValue().get(easybuyUser.getLoginname()+"la");
//        Map<Object , Object> m=(Map<Object , Object>)map.get("num");
        List<EasybuyProduct> list=(List<EasybuyProduct>)map.get("list");
//        m.put(id,num);
//        map.put("num",m);
        for (EasybuyProduct e:list){
            if (Integer.parseInt(e.getId())==id){
                e.setNum(num);
            }
        }
        redisTemplate.opsForValue().set(easybuyUser.getLoginname()+"la",map);
        Map<String ,String> mm=new HashMap<>();
        mm.put("msg","操作成功");
        return JSONArray.toJSON(mm);
    }



    @RequestMapping(value = "/selectPAll")
    public PageInfo<EasybuyProduct> selectPAll(int pageNum){
        return easybuyProductService.selectAll(pageNum,5);
    }

    @RequestMapping(value = "/updatePbyid")
    public Object updatePbyid(EasybuyProduct easybuyProduct){
        int a = easybuyProductService.updatePbyid(easybuyProduct);
        if(a>0){
            return JSONArray.toJSON("true");
        }else {
            return JSONArray.toJSON("false");
        }
    }

    @RequestMapping(value = "/deletePbyid")
    public Object deletePbyid(int id){
        int a = easybuyProductService.updataIsdelete(id);
        if(a>0){
            return JSONArray.toJSON("true");
        }else {
            return JSONArray.toJSON("false");
        }
    }

    @RequestMapping(value = "/selectbyid")
    public Object selectbyid(int id){
        return JSONArray.toJSON(easybuyProductService.selectById(id));
    }


    @RequestMapping(value = "/updateSP")
    public Object updateSP(EasybuyProduct easybuyProduct,@RequestParam("file") MultipartFile file) throws IOException {
        System.out.println("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++");
        if(file!=null && !file.equals("")){
            //获取上传的文件流
            InputStream inputStream=file.getInputStream();
            //获取上传的文件名
            String filename=file.getOriginalFilename();
            //截取后缀
            String suffix=filename.substring(filename.lastIndexOf("."));
            //使用时间戳拼接后缀，生成一个不重复的文件名
            String finalName=System.currentTimeMillis()+suffix;
            //调用自定义的FTP工具类上传文件
            FTPUtil.uploadFile(finalName,inputStream);

            easybuyProduct.setFilename(finalName);
        }


        int a = easybuyProductService.updatePbyid(easybuyProduct);
        if(a>0){
            return JSONArray.toJSON("true");
        }else {
            return JSONArray.toJSON("false");
        }
    }

    @RequestMapping(value = "/addSP")
    public Object addSP(EasybuyProduct easybuyProduct, @RequestParam("file") MultipartFile file) throws IOException {
        if(file!=null && !file.equals("")){
            //获取上传的文件流
            InputStream inputStream=file.getInputStream();
            //获取上传的文件名
            String filename=file.getOriginalFilename();
            //截取后缀
            String suffix=filename.substring(filename.lastIndexOf("."));
            //使用时间戳拼接后缀，生成一个不重复的文件名
            String finalName=System.currentTimeMillis()+suffix;
            //调用自定义的FTP工具类上传文件
            FTPUtil.uploadFile(finalName,inputStream);

            easybuyProduct.setFilename(finalName);
        }


        int a = easybuyProductService.insertSP(easybuyProduct);
        if(a>0){
            return JSONArray.toJSON("true");
        }else {
            return JSONArray.toJSON("false");
        }
    }


}
